import './index.scss'
import Go from './go'
// import './index.scss'

import sty from './index.module.scss'
import { Link } from 'react-router-dom'
import { useState } from 'react'
import { useEffect } from 'react'
import { useRef } from 'react'
import { useHistory } from 'react-router-dom'

// 注意：样式同名冲突和引入顺序有关系，后引入的会覆盖先引入的
/**
 *
 * @param {*} props
 * @returns
 */
function NotFound(props) {
  const [count, setCount] = useState(6)
  const timerRef = useRef(-1)
  const history = useHistory()

  useEffect(() => {
    timerRef.current = setInterval(() => {
      // console.log('定时器在执行')
      setCount((count) => count - 1)
    }, 1000)

    // 因为依赖项为空数组，所以，该返回的清理函数，只会在组件卸载时执行
    return () => {
      // console.log('404 页面卸载')
      clearInterval(timerRef.current)
    }
  }, [])

  useEffect(() => {
    if (count === 0) {
      history.replace('/home')
    }
  }, [count, history])
  return (
    // <div className="red">
    //   <p className={sty.ot}>404</p>
    //   <p className="meng wang">哈哈😄</p>
    //   <Go />
    // </div>
    <div className={sty.root}>
      <h1>对不起，您访问的页面不存在~</h1>
      <p>
        将在 {count} 秒后，返回首页（或者：点击立即返回
        <Link to="/home">首页</Link>）
      </p>
      <Test1 />
      <hr />
      {/* <Test2 /> */}
    </div>
  )
}

// 测试
const Test1 = () => {
  const [count, setCount] = useState(0)

  // 3 秒后，获取 count 值
  const getCount = () => {
    setTimeout(() => {
      console.log(count)
    }, 3000)
  }

  // 计数器 +1
  const handleClick = () => {
    setCount(count + 1)
  }

  return (
    <div>
      <button onClick={handleClick}>+1</button>
      <button onClick={getCount}>延迟获取 count 值</button>
      <h1>计数器：{count}</h1>
    </div>
  )
}

const Test2 = () => {
  const [count, setCount] = useState(0)
  // let timerId = -1
  const timerRef = useRef(-1)

  useEffect(() => {
    timerRef.current = setInterval(() => {
      console.log('interval')
    }, 1000)
    // console.log(timerId)
  }, [])

  const clear = () => {
    // console.log(timerId)
    clearInterval(timerRef.current)
  }

  const handleClick = () => {
    setCount(count + 1)
  }

  return (
    <div>
      <button onClick={handleClick}>+1</button>
      <button onClick={clear}>清理定时器</button>
      <h1>计数器：{count}</h1>
    </div>
  )
}

export default NotFound
